package core.java.test.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 描述：
 *
 * @author liuchuang
 * @date 2021/11/1 9:41
 */
public class ProxyTest1 {

    private static void mtd(Object obj) {
        System.out.println(((InterfaceTest) obj).plusOne());
    }

    public static void main(String[] args) {
        InvocationHandler handler = new TargetHandler(new ClassTest(1));
        Object object = Proxy
            .newProxyInstance(handler.getClass().getClassLoader(), new Class[]{InterfaceTest.class},
                handler);
        mtd(object);
    }

}

class ClassTest implements InterfaceTest {

    private int value;

    ClassTest(int value) {
        this.value = value;
    }

    /**
     * 将值加一返回
     *
     * @return 返回
     */
    @Override
    public int plusOne() {
        return value + 1;
    }

    @Override
    public String toString() {
        return String.valueOf(this.value);
    }
}

class TargetHandler implements InvocationHandler {

    private Object target;

    TargetHandler(Object t) {
        this.target = t;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.print(this.target + "." + method.getName() + "(");
        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                if (i > 0) {
                    System.out.print(", ");
                }
                System.out.print(args[i]);
            }
        }
        System.out.print(")=");
        return method.invoke(target, args);
    }
}


